layui.define(['table', 'form', 'laypage', 'laytpl', 'layer', 'laydate'], function (exp) {
    var table = layui.table
        , form = layui.form
        , $ = layui.$
        , laydate = layui.laydate
        , layer = layui.layer
        , laytpl = layui.laytpl;

    // 渲染数据表格
    let usersTable = table.render({
        id: 'usersTable',
        elem: '#users-table',
        url: '/user/search',
        method: 'post',
        toolbar: "#users-toolbar",
        defaultToolbar: ['filter', 'print'],
        request: {
            pageName: 'page' // 页码的参数名称，默认：page
            , limitName: 'size' // 每页数据量的参数名，默认：limit
        },
        parseData: function (res) {
            return {
                "data": res.payload.records,
                'code': res.code,
                'msg': res.msg,
                "count": res.payload.total
            }
        },
        response: {
            statusCode: 200
        },
        loading: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {type: 'numbers', field: 'id', sort: true, title: '序号', align: 'center', width: '5%'},
            {field: 'username', align: 'center', title: '用户名'},
            {field: 'realName', align: 'center', title: '真实姓名'},
            {align: 'center', title: '性别', field: 'sex', templet: function (d) {
                    if (d.sex === '男') {
                        return '<span class="layui-badge layui-bg-blue">' + d.sex + '</span>';
                    } else {
                        return '<span class="layui-badge layui-bg-green">' + d.sex + '</span>'
                    }
                }
            },
            {align: 'center', title: '审核状态', field: 'register', templet: function (d) {
                    if (d.register === 'REGISTER_YES') {
                        return '<span class="layui-badge layui-bg-green">已通过</span>';
                    } else if (d.register === 'REGISTER_NO') {
                        return '<span class="layui-badge">未通过</span>'
                    } else {
                        return '<span class="layui-badge layui-bg-gray">未审核</span>'
                    }
                }
            },
            {align: 'center', title: '权限', field: 'roleName', templet: function (d) {
                    if (d.roleName === 'ROLE_SUPER') {
                        return '<span class="layui-badge">超级管理员</span>';
                    } else if (d.roleName === 'ROLE_ADMIN') {
                        return '<span class="layui-badge layui-bg-orange">普通管理员</span>'
                    } else {
                        return '<span class="layui-badge layui-bg-cyan">普通用户</span>'
                    }
                }
            },
            {title: '操作', align: 'center', fixed: 'right', toolbar: '#users-bar', width: 320}
        ]],
        page: true,
        limits: [2, 4, 6, 8, 10, 20]
        , text: {
            none: '还没有用户!'
        }, done: function (res, curr, count) {
            this.where = {};
        }
    });

    // 监听列工具条
    table.on('tool(users-table)', function (obj) {
        const data = obj.data,
            event = obj.event,
            tr = obj.tr;
        if (event === 'root') {
            const loadIndex = layer.load();
            let b;
            let roleName = data.roleName;
            if (roleName === 'ROLE_USER') {
                b = '管理员';
                roleName = 'ROLE_ADMIN';
            } else {
                b = '普通用户';
                roleName = 'ROLE_USER';
            }
            $.post('/user/root/' + data.id, {"role": roleName}, function (result) {
                layer.close(loadIndex)
                if (b === '管理员') {
                    $(tr[2]).find('button[lay-event="root"]').attr('class', "layui-btn layui-btn-normal layui-btn-xs")
                    $(tr[2]).find('button[lay-event="root"]').html("<i class=\"layui-icon layui-icon-username\"></i>设为普通用户")
                    $(tr[2]).find('button[lay-event="del"]').attr('class', "layui-btn layui-btn-danger layui-btn-xs layui-btn-disabled").prop('disabled', true)
                } else {
                    $(tr[2]).find('button[lay-event="root"]').attr('class', "layui-btn layui-btn-normal layui-bg-orange layui-btn-xs")
                    $(tr[2]).find('button[lay-event="root"]').html("<i class=\"layui-icon layui-icon-username\"></i>设为管理员")
                    $(tr[2]).find('button[lay-event="del"]').attr('class', "layui-btn layui-btn-danger layui-btn-xs").prop('disabled', false)
                }

                obj.update({
                    roleName: roleName
                })
            })
        } else if (event === 'del') {
            let loadIndex = layer.load();
            $.post('/user/delete/' + data.id, function (result) {
                layer.close(loadIndex);
                if (result.success) {
                    layer.msg('删除成功!');
                    obj.del()
                } else {
                    layer.msg(result.msg)
                }
            })
        } else if (event === 'register') {
            let loadIndex = layer.load();
            $.post('/user/audited/' + data.id, {"register": "REGISTER_YES"}, function (result) {
                layer.close(loadIndex);

                if (result.success) {
                    $(tr[2]).find('button[lay-event="register"]').addClass('layui-btn-disabled').prop('disabled', true)
                    $(tr[2]).find('button[lay-event="notRegister"]').removeClass('layui-btn-disabled').prop('disabled', false)
                    obj.update({
                        register: "REGISTER_YES"
                    })
                }

            })
        } else if (event === 'notRegister') {
            let loadIndex = layer.load();
            $.post('/user/audited/' + data.id, {"register": "REGISTER_NO"}, function (result) {
                layer.close(loadIndex);

                if (result.success) {
                    $(tr[2]).find('button[lay-event="notRegister"]').addClass('layui-btn-disabled').prop('disabled', true)
                    $(tr[2]).find('button[lay-event="register"]').removeClass('layui-btn-disabled').prop('disabled', false)
                    obj.update({
                        register: "REGISTER_NO"
                    })
                }

            })
        }
    });

    // 监听左上工具条
    table.on('toolbar(users-table)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        switch(obj.event){
            case 'delete':
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择!', {icon: 5});
                    return;
                }
                layer.confirm('确定批量删除他们吗?', {icon: 3, title:'确认'}, function(index) {
                    var data = checkStatus.data
                        , ids = []
                        , loadIndex;
                    $.each(data, function (index, value) {
                        ids.push(value.id)
                    });
                    loadIndex = layer.load(1, {
                        shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                    $.post('/user/delete/more', {ids: ids}, function (result) {
                        layer.close(loadIndex);
                        if (result.success) {
                            layer.msg('批量删除成功!', {time: 1500});
                            usersTable.reload({
                                where: {
                                    page: 1,
                                    size: 10
                                }
                            })
                        } else {
                            layer.msg('删除失败!', {time: 1500});
                            usersTable.reload({
                                where: {
                                    page: 1,
                                    size: 10
                                }
                            })
                        }
                    })
                    layer.close(index);
                });
                break;
            case 'pass':
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择!', {icon: 5});
                    return;
                }
                layer.confirm('确定批量通过他们吗?', {icon: 3, title:'确认'}, function(index) {
                    var data = checkStatus.data
                        , ids = []
                        , loadIndex;
                    $.each(data, function (index, value) {
                        ids.push(value.id)
                    });
                    loadIndex = layer.load(1, {
                        shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                    $.post('/user/audited/more', {ids: ids, "register": "REGISTER_YES"}, function (result) {
                        layer.close(loadIndex)
                        if (result.success) {
                            layer.msg('批量同意成功!', {time: 1500});
                        } else {
                            layer.msg(result.msg, {time: 1500})
                        }
                        usersTable.reload({
                            where: {
                                page: 1,
                                size: 10
                            }
                        })
                    })
                    layer.close(index);
                });
                break;
            case 'notPass':
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择!', {icon: 5});
                    return;
                }
                layer.confirm('确定批量否决他们吗?', {icon: 3, title:'确认'}, function(index) {
                    var data = checkStatus.data
                        , ids = []
                        , loadIndex;
                    loadIndex = layer.load();
                    $.each(data, function (index, value) {
                        ids.push(value.id)
                    });
                    $.post('/user/audited/more', {ids: ids, "register": "REGISTER_NO"}, function (result) {
                        layer.close(loadIndex)
                        if (result.success) {
                            layer.msg('批量否决成功!', {time: 1500});
                        } else {
                            layer.msg(result.msg, {time: 1500})
                        }
                        usersTable.reload({
                            where: {
                                page: 1,
                                size: 10
                            }
                        })
                    })
                    layer.close(index);
                });
                break;
        };
    });

    // 查询工具
    form.on('submit(search-users)', function (data) {
        table.reload('usersTable', {
            where: {
                username: data.field['username'],
                realName: data.field['realName'],
                sex: data.field['sex'],
                register: data.field['register'],
                roles: data.field['roles']
            }
        });
        form.render();
    });

    // 重置查询
    form.on('submit(users-search)', function (data) {
        form.val("users-form", {
            "username": ""
            ,"realName": ""
            , "sex": ""
            , "register": ""
            , "roles": ""
        });
        usersTable.reload({
            where: {
                username: null,
                realName: null,
                sex: null,
                register: null,
                roles: null
            }
        });
        form.render();
    })

    exp('users', {});
});